package com.znzz.controller;

import com.znzz.entity.Files;
import com.znzz.service.FilesService;
import com.znzz.utils.DateUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;

/**
 * 上传文件控制器
 */

@Controller
@RequestMapping(path = "/user")
public class UploadController {

//    protected static final Logger logger= (Logger) LoggerFactory.getLogger(Files.class);

    @Autowired
    private FilesService filesService;

    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public ModelAndView uploadFiles(@RequestParam(name = "fileName") String fileTitle, @RequestParam(name = "files") MultipartFile files, ModelAndView mv, HttpServletRequest request) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/upload/");
        System.out.println("path:" + path);
        //通过该路径查找该文件
        File file = new File(path);
        //如果该文件不存在于此，就创建一个该文件夹
        if (!file.exists()) {
            file.mkdir();
        }
        String fileName = files.getOriginalFilename();
        System.out.println("fileName:" + fileName);

        //如果每次都上传同一个文件，则需要保证文件名的唯一性
        UUID uuid = UUID.randomUUID();
        //生成的uuid中有-，需要使用空字符串替换掉
        String id = uuid.toString().replace("-", "");
        //使用下划线将生成的uuid与文件名拼接起来
        String uniqueFileName = id + "_" + fileName;
        System.out.println("uniqueFileName:" + uniqueFileName);
        File saveFile = new File(path, uniqueFileName);
        System.out.println("savePath:" + saveFile);
        files.transferTo(saveFile);

        Files fileItems = new Files();
        fileItems.setFileName(fileTitle);
        System.out.println("fileTitle:" + fileTitle);
        fileItems.setFileAddress(saveFile.toString());
        fileItems.setUploadTime(DateUtil.SimpleDateFormat(new Date()));
        fileItems.setFileSize(saveFile.length()/1024);
        fileItems.setPrefixName(uniqueFileName);
        fileItems.setDownloadCount(0L);//初次保存文件，下载次数默认为0
        System.out.println("fileSize:" + saveFile.length()/1024);

        if (filesService.saveFiles(fileItems)) {
            System.out.println("保存成功");
            mv.setViewName("success");
            return mv;
        } else {
            return null;
        }
    }


    @RequestMapping(path = "/showAllFiles")
    public String showAllFiles(Model model) {
        List<Files> filesList = filesService.queryFiles();
        model.addAttribute("filesList", filesList);
        return "showFiles";
    }

    @RequestMapping(path = "/viewPic")
    public ModelAndView viewFileDetail(ModelAndView mv, @RequestParam(name = "id") Integer uid) {
        Files file = filesService.findFileById(uid);
        System.out.println(file.getFileAddress());
        mv.addObject("fileItem", file);
        mv.setViewName("fileDetail");
        return mv;
    }




}
